package com.sright.bcard.common.biz.manager.impl;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.sright.bcard.common.biz.manager.DingTalkManager;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Component
@Slf4j
public class DingTalkManagerImpl implements DingTalkManager {
    @Value("${DINGTALK_ROBOT_TOKEN}")
    private String token;

    @Value("${DINGTALK_ROBOT_SECRET}")
    private String secret;

    @Override
    public OapiRobotSendResponse sendGroupMessage(String content) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, ApiException {
        //获取签名
        Long timestamp = System.currentTimeMillis();
        String sign = sign(timestamp);

        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?access_token=" + token + "&timestamp=" +timestamp + "&sign=" + sign);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("text");
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(content);
        request.setText(text);
        OapiRobotSendResponse response = client.execute(request);
        if (response.getErrcode() != 0) {
            log.info("钉钉推送失败 : {}", response.getErrmsg());
        }
        return response;
    }

    public String sign(Long timestamp) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
        return sign;
    }
}
